package org.swift.mashup.wsdl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;

import org.apache.axiom.attachments.utils.IOUtils;
import org.apache.axis2.AxisFault;
import org.swift.commons.client.Call;
import org.swift.commons.client.RestCall;

import com.eviware.soapui.impl.wsdl.support.PathUtils;
import com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader;
import com.eviware.soapui.model.ModelItem;

/**
 * Same as the soapui wsdl loader except this one will timeout if the wsdl
 * doesn't exist.
 * 
 * @author Jon Roberts
 * 
 */
public class SwiftUrlWsdlLoader extends UrlWsdlLoader {

	public SwiftUrlWsdlLoader(String url) {
		super(url);
	}

	public SwiftUrlWsdlLoader(String url, ModelItem contextModelItem) {
		super(url, contextModelItem);
	}

	@Override
	public synchronized InputStream load(String url) throws Exception {
		if (!PathUtils.isHttpPath(url)) {
			try {
				File file = new File(url.replace('/', File.separatorChar));
				if (file.exists())
					url = file.toURI().toURL().toString();
			} catch (Exception e) {
			}
		}

		if (urlCache.containsKey(url)) {
			setNewBaseURI(url);
			return new ByteArrayInputStream(urlCache.get(url));
		}

		if (url.startsWith("file:")) {
			return handleFile(url);
		}

		log.debug("Getting wsdl component from [" + url + "]");
		
		byte[] content = getWsdl(url);
		if (content != null) {				
			urlCache.put(url, content);
			return new ByteArrayInputStream(content);
		} else {
			throw new Exception("Failed to load url: " + url);
		}
	 
	}

	private byte[] getWsdl(String url) throws AxisFault, IOException {
		Call call = new RestCall(url, "GET", 120000);
		return IOUtils.getStreamAsByteArray(
					call.sendRecieve(Collections.<String, Object>emptyMap()));
	}

	

}
